using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Data;
using ctsu.Security;
using ctsu.Shared;

using Syncfusion.Windows.Forms.Tools;


namespace ctsu.Admin.BusLogic
{

	public class BLFormProtocolVisitAdmissionImpl : BLFormBaseImpl
	{
		private bool _ignoreEvent = false;
		enum SearchTypes { Standard, Patient, Protocol, Investigator };
		private SearchTypes _searchType = SearchTypes.Standard;

		#region control references
		private CheckBox _pending;
		private DateTimePickerAdv _visitDate;
		private DateTimePickerAdv _dischargeDate;
		private Syncfusion.Windows.Forms.Tools.NumericUpDownExt _ctlInHr;
		private Syncfusion.Windows.Forms.Tools.NumericUpDownExt _ctlInMin;
		private Syncfusion.Windows.Forms.Tools.NumericUpDownExt _ctlOutHr;
		private Syncfusion.Windows.Forms.Tools.NumericUpDownExt _ctlOutMin;
		private RadioButton _inAM;
		private RadioButton _outAM;
		private RadioButton _inPM;
		private RadioButton _outPM;
		protected TextBox _patient;
		private TextBox _mrn;
		private TextBox _patientName;
		private TextBox _dob;
		private Button _btnPatient;
		private Button _btnProtocol;
		protected TextBox _protocol;
		//protected TextBox _spid;
		private TextBox _protocolNumber;
		private TextBox _investigator;
		private TextBox _title;
		private ComboBox _visitType;
		private ComboBox _site;
		#endregion control references

		#region initialize
		public BLFormProtocolVisitAdmissionImpl(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{

		}

		//hook these events so we get change effects
		protected override void _vcManager_OnAfterHookEvents()
		{
			_pending = (CheckBox)Forms.Utils.GetControlByName("Pending", this._form.Controls);
			_visitDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("VisitDate", this._form.Controls);
			_dischargeDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("DischargeDate", this._form.Controls);
			_ctlInHr = (NumericUpDownExt)Forms.Utils.GetControlByName("InHr", this._form.Controls);
			_ctlInMin = (NumericUpDownExt)Forms.Utils.GetControlByName("InMin", this._form.Controls);
			_inAM = (RadioButton)Forms.Utils.GetControlByName("InAM", this._form.Controls);
			_inPM = (RadioButton)Forms.Utils.GetControlByName("InPM", this._form.Controls);
			_ctlOutHr = (NumericUpDownExt)Forms.Utils.GetControlByName("OutHr", this._form.Controls);
			_ctlOutMin = (NumericUpDownExt)Forms.Utils.GetControlByName("OutMin", this._form.Controls);
			_outAM = (RadioButton)Forms.Utils.GetControlByName("OutAM", this._form.Controls);
			_outPM = (RadioButton)Forms.Utils.GetControlByName("OutPM", this._form.Controls);
			_patient = (TextBox)Forms.Utils.GetControlByName("Patient", this._form.Controls);
			_mrn = (TextBox)Forms.Utils.GetControlByName("MRN", this._form.Controls);
			_patientName = (TextBox)Forms.Utils.GetControlByName("PatientName", this._form.Controls);
			_dob = (TextBox)Forms.Utils.GetControlByName("DOB", this._form.Controls);
			_btnPatient = (Button)Forms.Utils.GetControlByName("btnPatient", this._form.Controls);
			_btnProtocol = (Button)Forms.Utils.GetControlByName("btnProtocol", this._form.Controls);
			_protocol = (TextBox)Forms.Utils.GetControlByName("Protocol", this._form.Controls);
			//_spid = (TextBox)Forms.Utils.GetControlByName("SPID", this._form.Controls);
			_protocolNumber = (TextBox)Forms.Utils.GetControlByName("ProtocolNumber", this._form.Controls);
			_investigator = (TextBox)Forms.Utils.GetControlByName("Investigator", this._form.Controls);
			_title = (TextBox)Forms.Utils.GetControlByName("Title", this._form.Controls);
			_visitType = (ComboBox)Forms.Utils.GetControlByName("AdmissionVisitType", this._form.Controls);
			_site = (ComboBox)Forms.Utils.GetControlByName("PSite", this._form.Controls);

			_visitType.SelectedIndexChanged += new EventHandler(_visitType_SelectedIndexChanged);
			_ctlInHr.ValueChanged += new EventHandler(Central_ValueChanged);
			_ctlInHr.ValueChanged += new EventHandler(_hr_ValueChanged);
			_ctlInHr.Enter += new EventHandler(_ctlInHr_Enter);

			_ctlInMin.ValueChanged += new EventHandler(Central_ValueChanged);
			_ctlInMin.ValueChanged += new EventHandler(_min_ValueChanged);
			_ctlInMin.Enter += new EventHandler(_ctlInMin_Enter);

			_inAM.CheckedChanged += new EventHandler(Central_ValueChanged);
			_inPM.CheckedChanged += new EventHandler(Central_ValueChanged);

			_ctlOutHr.ValueChanged += new EventHandler(Central_ValueChanged);
			_ctlOutHr.ValueChanged += new EventHandler(_hr_ValueChanged);
			_ctlOutHr.Enter += new EventHandler(_ctlOutHr_Enter);

			_ctlOutMin.ValueChanged += new EventHandler(Central_ValueChanged);
			_ctlOutMin.ValueChanged += new EventHandler(_min_ValueChanged);
			_ctlOutMin.Enter += new EventHandler(_ctlOutMin_Enter);

			_outAM.CheckedChanged += new EventHandler(Central_ValueChanged);
			_outPM.CheckedChanged += new EventHandler(Central_ValueChanged);
			_patient.TextChanged += new EventHandler(Central_TextChanged);
			_protocol.TextChanged += new EventHandler(Central_TextChanged);

			_visitDate.ValueChanged += new EventHandler(_visitDate_ValueChanged);
			_pending.CheckedChanged += new EventHandler(_pending_CheckedChanged);
			_dischargeDate.ValueChanged += new EventHandler(_dischargeDate_ValueChanged);
			//hook password text changed
			base._vcManager_OnAfterHookEvents();
		}

		private void _ctlInHr_Enter(object sender, EventArgs e)
		{
			string s = _ctlInHr.Value.ToString();
			_ctlInHr.Select(0, s.Length);
		}

		private void _ctlInMin_Enter(object sender, EventArgs e)
		{
			string s = _ctlInMin.Value.ToString();
			_ctlInMin.Select(0, s.Length);
		}

		private void _ctlOutHr_Enter(object sender, EventArgs e)
		{
			string s = _ctlOutHr.Value.ToString();
			_ctlOutHr.Select(0, s.Length);
		}

		private void _ctlOutMin_Enter(object sender, EventArgs e)
		{
			string s = _ctlOutMin.Value.ToString();
			_ctlOutMin.Select(0, s.Length);
		}
		#endregion initialize

		public override bool Remove()
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("Press 'Yes' to confirm the removal of Admission Visit ID: " + this._currentPrimaryID.ToString());
			sb.Append(Environment.NewLine);
			sb.Append("or press 'No' to cancel.");
			if (MessageBox.Show(this._form, sb.ToString(), "Confirm Admission Removal", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
				return false;

			sb.Remove(0, sb.Length);

			//this is used as a parameter for table grid display
			DbTableChange tableChange = DbTableChange.Update;

			string sql = "DELETE FROM ProtocolVisitAdmission WHERE ID=" + this._currentPrimaryID;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				int i = (int)DataAccess.ExecuteNonQuery(CommandType.Text, sql);
				if (i == 1)
				{
					sb.Append("Admission ID: " + this._currentPrimaryID.ToString() + " was deleted.");
					this._fcManager.CurrentRow.Delete();
					this.ResetToOriginal();
					MessageBox.Show(this._form, sb.ToString(), "Confirm Admission Removal", MessageBoxButtons.OK, MessageBoxIcon.Information);

					BLTableChangeAdvEventArgs args = new BLTableChangeAdvEventArgs(this._formInfo.TableName, tableChange, this._currentPrimaryID - 1);

					this.FireTableChange(args);
				}
				else
				{
					sb.Append("Admission ID: " + this._currentPrimaryID.ToString() + " was not deleted.");
					sb.Append(Environment.NewLine);
					sb.Append(Shared.Constants.NotifySupportImmediate);
					MessageBox.Show(this._form, sb.ToString(), "Admission Removal", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
				return true;
			}
			catch (Exception ex)
			{
				sb.Append("Could not delete admission!");
				sb.Append(Environment.NewLine);
				if (ex.Message.IndexOf("COLUMN REFERENCE constraint") > 0)
				{
					sb.Append("There is a record in another table (most likely an acillary record)");
					sb.Append(Environment.NewLine);
					sb.Append("that currently references this record!");
				}
				else
					sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Delete Admission Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void _visitType_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (_visitType.SelectedIndex == -1)
				return;
			NameVal nv = (NameVal)_visitType.SelectedItem;

			switch (nv.Val)
			{
				case 2:
					_site.SelectedValue = 2;
					break;
				case 3:
					_site.SelectedValue = 5;
					break;
			}

		}

		private void _pending_CheckedChanged(object sender, EventArgs e)
		{
			if (this._formMode == EditMode.Load)
				return;
			if (_ignoreEvent)
			{
				_ignoreEvent = false;
				return;
			}
			StringBuilder sb = new StringBuilder();
			if (_pending.Checked)
			{
				if (!_dischargeDate.IsNullDate)
				{
					sb.Append("Checking the pending check box will remove the current discharge date.");
					sb.Append(Environment.NewLine);
					sb.Append("Do you want to continue?");
					if (MessageBox.Show(this._form, sb.ToString(), "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
					{
						_ignoreEvent = true;
						_pending.Checked = false;
						return;
					}
					_dischargeDate.IsNullDate = true;
				}
			}
		}

		private void _visitDate_ValueChanged(object sender, EventArgs e)
		{
			if (this._formMode == EditMode.Load)
				return;
			if (!_visitDate.IsNullDate)
			{
				_dischargeDate.Value = _visitDate.Value;
			}
		}

		private void _dischargeDate_ValueChanged(object sender, EventArgs e)
		{
			if (this._formMode == EditMode.Load)
				return;
			if (!_dischargeDate.IsNullDate)
			{
				if (_pending.Checked)
					_pending.Checked = false;
			}
			if (_dischargeDate.IsNullDate || _visitDate.IsNullDate)
			{
				return;
			}

			DateTime dtAdmit = _visitDate.Value.Date;
			DateTime dtDisch = _dischargeDate.Value.Date;

			if (dtDisch.CompareTo(dtAdmit) > 0)
			{
				TimeSpan ts = dtDisch - dtAdmit;
				if (ts.Days > 14)
					MessageBox.Show("Admission stay is more than 14 days!");

			}

		}

		#region time and ancil only change events
		private void _min_ValueChanged(object sender, EventArgs e)
		{
			NumericUpDownExt hr = null;
			NumericUpDownExt min = (NumericUpDownExt)sender;
			if (min.Name.StartsWith("In"))
				hr = this._ctlInHr;
			else
				hr = this._ctlOutHr;

			if (hr.Value == 0 && min.Value > 0)
			{
				min.Value = 0;
				MessageBox.Show("The hours must be greater than 0 before setting the minutes");
				return;
			}

		}

		private void _hr_ValueChanged(object sender, EventArgs e)
		{
			NumericUpDownExt min = null;
			NumericUpDownExt hr = (NumericUpDownExt)sender;
			if (hr.Name.StartsWith("In"))
				min = this._ctlInMin;
			else
				min = this._ctlOutMin;

			if (hr.Value == 0 && min.Value > 0)
			{
				min.Value = 0;
			}
		}
		#endregion time and ancil only change events

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_ctlInHr.Enabled = enable;
			_ctlInMin.Enabled = enable;
			_inAM.Enabled = enable;
			_inPM.Enabled = enable;
			_ctlOutHr.Enabled = enable;
			_ctlOutMin.Enabled = enable;
			_outAM.Enabled = enable;
			_outPM.Enabled = enable;
			_mrn.Enabled = enable;
			_patientName.Enabled = enable;
			_dob.Enabled = enable;
			_btnPatient.Enabled = enable;
			_btnProtocol.Enabled = enable;
			//_spid.Enabled = enable;
			_protocolNumber.Enabled = enable;
			_investigator.Enabled = enable;
			_title.Enabled = enable;
		}

		#region display data
		public override void DisplayData()
		{
			base.DisplayData();

			FieldContext fc = (FieldContext)this._fcManager.Item("TimeIn");
			DisplayTimeIn(fc);
			fc = (FieldContext)this._fcManager.Item("TimeOut");
			DisplayTimeOut(fc);
			fc = (FieldContext)this._fcManager.Item("Patient");
			DisplayPatient(fc);
			fc = (FieldContext)this._fcManager.Item("Protocol");
			DisplayProtocol(fc);

		}

		protected override void ClearAllControls()
		{
			base.ClearAllControls();
			ClearNonFieldContextControls();
		}

		private void ClearNonFieldContextControls()
		{
			_ctlInHr.Value = 0;
			_ctlInMin.Value = 0;
			_inAM.Checked = true;
			_ctlOutHr.Value = 0;
			_ctlOutMin.Value = 0;
			_outAM.Checked = true;
			_mrn.Text = "";
			_patientName.Text = "";
			_dob.Text = "";
			//_spid.Text = "";
			_protocolNumber.Text = "";
			_investigator.Text = "";
			_title.Text = "";
		}

		private void DisplayPatient(FieldContext fc)
		{
			StringBuilder sb = new StringBuilder();
			if (_fcManager.CurrentRow[fc.Column.ColumnName] is System.DBNull)
			{
				this._patient.Text = "";
				this._mrn.Text = "";
				this._patientName.Text = "";
				this._dob.Text = "";
				return;
			}

			int id = (int)_fcManager.CurrentRow[fc.Column.ColumnName];
			GetPatientData(id);
		}

		private void DisplayProtocol(FieldContext fc)
		{
			StringBuilder sb = new StringBuilder();
			if (_fcManager.CurrentRow[fc.Column.ColumnName] is System.DBNull)
			{
				this._protocol.Text = "";
				//this._spid.Text = "";
				this._protocolNumber.Text = "";
				this._investigator.Text = "";
				this._title.Text = "";
				return;
			}

			int id = (int)_fcManager.CurrentRow[fc.Column.ColumnName];
			GetProtocolData(id);
		}

		private void DisplayTimeIn(FieldContext fc)
		{
			//enable/disable controls
			if (this._formMode == EditMode.Load)
			{
				this._ctlInHr.Enabled = false;
				this._ctlInMin.Enabled = false;
				this._inAM.Enabled = false;
				this._inPM.Enabled = false;
			}
			else
			{
				this._ctlInHr.Enabled = true;
				this._ctlInMin.Enabled = true;
				this._inAM.Enabled = true;
				this._inPM.Enabled = true;
			}

			fc.Control.Text = _fcManager.CurrentRow[fc.Column.ColumnName].ToString();
			string s = fc.Control.Text;
			if (s.Trim().Length == 0)
			{
				this._ctlInHr.Value = 0;
				this._ctlInMin.Value = 0;
				this._inAM.Checked = true;
			}
			else
			{
				//parse value									
				string hr = s.Substring(0, 2);
				string min = s.Substring(3, 2);
				string am = s.Substring(5, 1);
				this._ctlInHr.Value = Convert.ToInt32(hr);
				this._ctlInMin.Value = Convert.ToInt32(min);
				if (am == "a")
					this._inAM.Checked = true;
				else
					this._inPM.Checked = true;
			}

		}

		private void DisplayTimeOut(FieldContext fc)
		{
			//enable/disable controls
			if (this._formMode == EditMode.Load)
			{
				this._ctlOutHr.Enabled = false;
				this._ctlOutMin.Enabled = false;
				this._outAM.Enabled = false;
				this._outPM.Enabled = false;
			}
			else
			{
				this._ctlOutHr.Enabled = true;
				this._ctlOutMin.Enabled = true;
				this._outAM.Enabled = true;
				this._outPM.Enabled = true;
			}

			fc.Control.Text = _fcManager.CurrentRow[fc.Column.ColumnName].ToString();
			string s = fc.Control.Text;
			if (s.Trim().Length == 0)
			{
				this._ctlOutHr.Value = 0;
				this._ctlOutMin.Value = 0;
				this._outAM.Checked = true;
			}
			else
			{
				//parse value									
				string hr = s.Substring(0, 2);
				string min = s.Substring(3, 2);
				string am = s.Substring(5, 1);
				this._ctlOutHr.Value = Convert.ToInt32(hr);
				this._ctlOutMin.Value = Convert.ToInt32(min);
				if (am == "a")
					this._outAM.Checked = true;
				else
					this._outPM.Checked = true;
			}

		}
		#endregion display data

		#region verify
		protected override bool CheckWarning()
		{
			StringBuilder sb = new StringBuilder();
			string spName = "AdmissionWarningCheck";
			//SqlConnection conn = LoginForm.GetSqlConnection();			
			object[] paramObj = new object[3];
			paramObj[0] = int.Parse(this._patient.Text);
			paramObj[1] = int.Parse(this._protocol.Text);
			paramObj[2] = _visitDate.Value;
			IDataReader reader = null;
			try
			{
				//conn.Open();
				reader = DataAccess.GetDataReader(spName, paramObj);
				if (reader.Read())
				{
					sb.Append("WARNING: There is at least one other admission with the same date for the same patient for a different protocol.");
					sb.Append(Environment.NewLine);
					sb.Append("Admission ID: " + reader.GetInt32(0) + " has the same admission date," +
						" and patient for protocol: " + reader.GetString(1));
					sb.Append(Environment.NewLine);
					sb.Append("Do you want to continue saving this admission?");
					if (MessageBox.Show(this._form, sb.ToString(), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
						return true;
				}
				return false;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not check for warning.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "CheckWarning Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return true;
			}
			finally
			{
				if (reader != null)
					reader.Close();
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		protected override bool CheckDuplicate()
		{
			StringBuilder sb = new StringBuilder();
			string spName = "AdmissionDuplicateCheck";
			//SqlConnection conn = LoginForm.GetSqlConnection();			
			object[] paramObj = new object[3];
			paramObj[0] = int.Parse(this._patient.Text);
			paramObj[1] = int.Parse(this._protocol.Text);
			paramObj[2] = _visitDate.Value;
			IDataReader reader = null;
			try
			{
				//conn.Open();
				reader = DataAccess.GetDataReader(spName, paramObj);
				if (reader.Read())
				{
					sb.Append("Could not save admission.");
					sb.Append(Environment.NewLine);
					sb.Append("Admission ID: " + reader.GetInt32(0) + " has the same admission date," +
						" protocol and patient.");
					MessageBox.Show(this._form, sb.ToString(), "Duplicate", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return true;
				}
				return false;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not check for duplicate.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "CheckDuplicate Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return true;
			}
			finally
			{
				if (reader != null)
					reader.Close();
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		private bool ValidateProtocol(int id, out string message)
		{
			message = "";
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT p.IrbApproval,p.IrbRenewal,p.Incomplete " +
				" FROM Protocol p" +
				" WHERE p.ID = " + id;

			bool incomplete;
			DateTime dtApp = new DateTime(0);
			DateTime dtRen = new DateTime(0);
			DateTime dtLatest;

			if (this._visitDate.IsNullDate)
			{
				message = "You must enter a valid admission date.";
				return false;
			}

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					incomplete = false;
					if (!reader.IsDBNull(2))
						incomplete = reader.GetBoolean(2);
					if (incomplete)
					{
						message = "Protocol is incomplete.";
						return false;
					}

					if (!reader.IsDBNull(0))
						dtApp = reader.GetDateTime(0);
					if (!reader.IsDBNull(1))
						dtRen = reader.GetDateTime(1);

					if (dtApp.ToShortDateString() == "1/1/0001" && dtRen.ToShortDateString() == "1/1/0001")
					{
						message = "Both Irb Approval and Renewal dates are null.";
						return false;
					}

					if (dtApp.ToShortDateString() == "1/1/0001" || dtRen.ToShortDateString() == "1/1/0001")
					{
						if (dtApp.ToShortDateString() == "1/1/0001")
							dtLatest = dtRen;
						else
							dtLatest = dtApp;
					}
					else
					{
						dtLatest = dtApp;

						if (dtRen.CompareTo(dtApp) > 0)
							dtLatest = dtRen;
					}

					int year = dtLatest.Year;
					int mon = dtLatest.Month;
					int day = dtLatest.Day;
					int addDays = 364;

					if (DateTime.IsLeapYear(year))
					{
						if (mon < 3)
						{
							addDays = 365;

							//					if(mon == 2)
							//					{
							//						if(day == 29)
							//							addDays = 364;
							//					}					
						}
					}
					if (DateTime.IsLeapYear(year + 1))
					{
						if (mon > 2)
						{
							addDays = 365;
						}
					}

					dtLatest = dtLatest.AddDays(addDays);


					DateTime visit;

					//compare with visit date					
					if (!_dischargeDate.IsNullDate)
						visit = _dischargeDate.Value;
					else
						visit = _visitDate.Value;


					if (visit.CompareTo(dtLatest) > 0)
					{
						message = "Protocol has expired.  Expiration date is " + dtLatest.ToShortDateString();
						return false;
					}

					return true;
				}
				else
				{
					sb.Append("This should not happen.");
					sb.Append(Environment.NewLine);
					sb.Append("Function ValidateProtocol.");
					sb.Append(Environment.NewLine);
					sb.Append(Constants.NotifySupportImmediate);
					Exception ex = new Exception(sb.ToString());
					//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
					message = sb.ToString();
					return false;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocol for validation!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Protocol For Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				message = sb.ToString();
				return false;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		protected bool VerifyVisitType(Control ctl)
		{
			FieldContext fc = (FieldContext)ctl.Tag;

			DateTime vd = _visitDate.Value;
			DateTime beginValidatingDate = new DateTime(2008, 6, 1);

			//don't validate if visitdate is earlier than 6/1/08
			if (vd.CompareTo(beginValidatingDate) < 0)
				return true;

			if (_visitType.SelectedIndex == -1)
			{
				fc.ErrorMessage = Constants.ValidErrorRequiredEmpty;
				return false;
			}

			NameVal nv = (NameVal)_visitType.SelectedItem;
			if (nv.Val < 2)
			{
				fc.ErrorMessage = Constants.ValidErrorRequiredEmpty;
				return false;
			}

			int siteVal = 0;
			if (_site.SelectedIndex > -1)
			{
				NameVal nv2 = (NameVal)_site.SelectedItem;
				siteVal = nv2.Val;
			}

			switch (nv.Val)
			{
				case 2:
					if (!((siteVal == 2) || (siteVal == 3)))
					{
						fc.ErrorMessage = "Site must be '6Th Floor' or 'CAT/CR' for visit type 'On-Site Inpatient Day'";
						return false;
					}

					break;
				case 3:
					_site.SelectedValue = 5;
					break;
				case 4:
					if (!((siteVal == 5) || (siteVal == 6)))
					{
						fc.ErrorMessage = "Site must be 'Other' or 'Waltham' for visit type 'Off-Site Inpatient Day'";
						return false;
					}
					break;
			}

			return true;
		}

		protected bool VerifyComboAdv(Control ctl)
		{
			if (!VerifyCombo(ctl))
				return false;

			FieldContext fc = (FieldContext)ctl.Tag;
			int val = (int)fc.CurrentValue;
			if (val < 2)
			{
				fc.ErrorMessage = Constants.ValidErrorRequiredEmpty;
				return false;
			}
			return true;
		}

		protected bool VerifyPatient(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			//this will check for a selection
			if (!this.VerifyInt(ctl))
				return false;

			FieldContext fc = (FieldContext)ctl.Tag;

			int id = Convert.ToInt32(ctl.Text);
			//this is the misc account
			if (id == 5124)
				return true;

			DateTime dtVisit = this._visitDate.Value;
			DateTime dob = new DateTime(0);

			//SqlConnection conn = LoginForm.GetSqlConnection();
			string sql = "SELECT DOB FROM Patient WHERE ID=" + id;

			try
			{
				//conn.Open();
				object o = DataAccess.GetScalarObject(CommandType.Text, sql);

				if (o == System.DBNull.Value)
				{
					sb.Append("The date of birth is not entered for this patient.");
				}
				else
				{
					dob = Convert.ToDateTime(o);
					if (dob.CompareTo(dtVisit) > 0)
						return true;
					sb.Append("The date of birth, " + dob.ToShortDateString() + ", is not greater than the admit date.");
				}

				sb.Append(Environment.NewLine);
				sb.Append("Do you want to continue?");
				if (MessageBox.Show(this._form, sb.ToString(), "Patient DOB Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
				{
					fc.ErrorMessage = "Save was aborted by user!";
					return false;
				}
				return true;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not verify patient date of birth.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				fc.ErrorMessage = sb.ToString();
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		protected bool VerifyProtocol(Control ctl)
		{
			//this will check for a selection
			if (!this.VerifyInt(ctl))
				return false;

			FieldContext fc = (FieldContext)ctl.Tag;
			string message = "";
			int id = Convert.ToInt32(ctl.Text);
            //if (!ValidateProtocol(id, out message))
            //{
            //    fc.ErrorMessage = message;
            //    return false;
            //}
			return true;
		}

		protected bool VerifyCategory(Control ctl)
		{
			//this will check for a selection
			if (!this.VerifyComboAdv(ctl))
				return false;


			FieldContext fc = (FieldContext)ctl.Tag;
			int id = (int)fc.CurrentValue;

			if (id < 2 || id > 5)
			{
				fc.ErrorMessage = "Invalid value for category!";
				return false;
			}
			return true;
		}

		protected bool VerifyDates(Control ctl)
		{
			//this should be called for summary validation only
			//TODO - changing dates could affect related ancillaries
			FieldContext fc = (FieldContext)ctl.Tag;
			string field = fc.Column.ColumnName;

			if (field == "VisitDate")
			{

				//check for required and valid dates
				if (!this.VerifyDate(_visitDate))
					return false;

				//don't bother going any further if discharge is not entered
				if (_dischargeDate.IsNullDate)
					return true;
			}
			else
			{
				//allow blank discharge date if pending
				if (_pending.Checked)
				{
					if (_dischargeDate.IsNullDate)
						return true;
				}

				if (!this.VerifyDate(_dischargeDate))
					return false;
			}

			//allow blank discharge date if pending
			if (_pending.Checked)
			{
				if (_dischargeDate.IsNullDate)
					return true;
			}

			DateTime dtAdmit = _visitDate.Value.Date;
			DateTime dtDisch = _dischargeDate.Value.Date;

			if (dtAdmit.CompareTo(dtDisch) > -1)
			{
				fc.ErrorMessage = "Discharge Date must be later than Admit Date.";
				return false;
			}
			return true;
		}

		protected bool VerifyTimeIn(Control ctl)
		{
			//this is the hidden text control TimeIn
			FieldContext fc = (FieldContext)ctl.Tag;
			fc.Control.Text = "";

			int iHr = System.Convert.ToInt32(_ctlInHr.Value);
			int iMin = System.Convert.ToInt32(_ctlInMin.Value);

			if (fc.IsRequired)
			{
				if (iHr == 0 && iMin == 0)
				{
					fc.ErrorMessage = Constants.ValidErrorRequiredEmpty;
					return false;
				}
			}

			if (iHr == 0 && iMin != 0)
			{
				fc.ErrorMessage = "Invalid Time In\nHour cannot be zero.";
				return false;
			}

			string sMin = iMin.ToString("00");
			string sHr = iHr.ToString("00");

			if (_inAM.Checked)
				fc.Control.Text = sHr + ":" + sMin + "a";
			else
				fc.Control.Text = sHr + ":" + sMin + "p";

			//TODO return true here
			return true;
		}

		protected bool VerifyTimeOut(Control ctl)
		{
			//this is the hidden text control TimeOut
			FieldContext fc = (FieldContext)ctl.Tag;
			fc.Control.Text = "";

			int iHr = System.Convert.ToInt32(_ctlOutHr.Value);
			int iMin = System.Convert.ToInt32(_ctlOutMin.Value);

			if (fc.IsRequired)
			{
				if (iHr == 0 && iMin == 0)
				{
					fc.ErrorMessage = Constants.ValidErrorRequiredEmpty;
					return false;
				}
			}

			if (iHr == 0 && iMin == 0)
			{
				if (_pending.Checked)
					return true;
				else
				{
					fc.ErrorMessage = "Time out is required if the visit is not pending.";
					return false;
				}
			}

			if (iHr == 0 && iMin != 0)
			{
				fc.ErrorMessage = "Invalid Discharge Time\nHour cannot be zero.";
				return false;
			}

			string sMin = iMin.ToString("00");
			string sHr = iHr.ToString("00");

			if (_outAM.Checked)
				fc.Control.Text = sHr + ":" + sMin + "a";
			else
				fc.Control.Text = sHr + ":" + sMin + "p";

			//TODO return true here
			return true;
		}
		#endregion verify

		#region select
		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnPatient")
				SelectPatient();
			if (sender.Name == "btnProtocol")
				SelectProtocol();
			if (sender.Name == "btnNewPatient")
				DisplayPatientForm();
		}

		private void DisplayPatientForm()
		{
			StringBuilder sb = new StringBuilder();
			FormPatient fp = new FormPatient();

			//need to create instance for bl			
			FormInfoBase fi = this._formMain.GetFormInfo(1, true);

			//check for permission
			Permission permission = Forms.FormSecurity.GetFormAccess(fi, LoginForm.ApplicationSecurity.ApplicationUser);
			if (permission == Permission.AccessDenied)
			{
				MessageBox.Show(this._form, "You do not have access rights for form: " + fi.Name, "Access Denied");
				return;
			}

			DataTable dt = Forms.Utils.GetTableSchema(fi.TableName, null);
			Hashtable ht = this._formMain.GetFormsConfigUserOptions();

			BLFormPatientDialogImpl bl = new BLFormPatientDialogImpl(this._formMain, fp, fi, dt, permission, ht);

			//create controller
			FormBaseControllerImpl ctlr = new FormBaseControllerImpl(fp, bl);
			if (!bl.Initialize())
			{
				sb.Append("Could not load form!");
				sb.Append(Environment.NewLine);
				sb.Append(Constants.NotifySupport);
				MessageBox.Show(this._form, sb.ToString(), "Loading Form Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			fp.Controller = ctlr;

			//bl.FormIcon = Icon.FromHandle(((Bitmap)this.imgL1.Images[fi.ImageIndex]).GetHicon());
			bl.GridView += new BusinessLogicEvents.BLGridViewEventHandler(this._formMain.OnGridView);
			bl.TableChange += new ctsu.BaseForms.BusinessLogicEvents.BLTableChangeEventHandler(this._formMain.OnTableChange);

			fp.Activated += new EventHandler(fp_Activated);
			fp.ShowDialog(this._form);
			if (fp.DialogResult == DialogResult.OK)
				this.GetPatientData(fp.CurrentPrimaryID);

		}

		private void fp_Activated(object sender, EventArgs e)
		{
			FormPatient fp = (FormPatient)sender;
			BLFormPatientDialogImpl bl = (BLFormPatientDialogImpl)fp.Controller.BusinessLogic;
			bl.DisplayData();
		}

		private void SelectProtocol()
		{
			SelectProtocolDlg spd = new SelectProtocolDlg();
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				SelectProtocolStandard();
			else if (spd.SearchChoice == 1)
				SelectProtocolByInvestigator();
		}

		private void SelectByProtocol()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Protocol"];
			_searchType = SearchTypes.Protocol;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectByInvestigator()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Investigator"];
			_searchType = SearchTypes.Investigator;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display investigator seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectProtocolByInvestigator()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Investigator"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.ShowDialog(this._form);
				if (fs.DialogResult == DialogResult.OK)
				{
					int id = fs.SelectedID;
					GetProtocolData(id);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SelectProtocolStandard()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Protocol"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.ShowDialog(this._form);
				if (fs.DialogResult == DialogResult.OK)
				{
					Console.WriteLine("DialogResult.OK");
					int id = fs.SelectedID;
					GetProtocolData(id);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not display protocol seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void GetPatientActualProjectedPercent(int id)
		{
			string message = "";
			Control ctl = Forms.Utils.GetControlByName("Protocol", this._form.Controls);

			int percent = ProtocolUtils.GetPatientActualProjectedPercent(id, out message);

			if (percent == 0)
			{
				if (message.Length > 0)
					MessageBox.Show(this._form, message.ToString(), "Get Actual Projected Pateint Percentage Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			else
				this._form.errP.SetError(ctl, message);
		}

		private void GetProtocolData(int id)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT p.ID, p.ProtocolNumber, p.PCategory, p.PSite, " +
	                     "i.LastName + ', ' + i.FirstName AS Name, p.Title " + 
	                     "FROM Protocol p " +
	                     "INNER JOIN ProtocolStaff ps ON ps.ProtocolID= p.ID " +
	                     "INNER JOIN Investigator i ON i.ID = ps.InvestigatorID " +
		                 "WHERE p.ID = " + id +
		                 " AND (ps.StaffTypeID = 1 OR  ps.StaffTypeID = 4)";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				if (reader.Read())
				{
					this._protocol.Text = reader.GetInt32(0).ToString();
					//this._spid.Text = reader.GetInt32(1).ToString();
					
                    this._protocolNumber.Text = reader.GetString(1);
					this._investigator.Text = reader.GetString(4);
					this._title.Text = reader.GetString(5);
                    //if (this._formMode == EditMode.New)
                    //{
                    //    ComboBox cbo = (ComboBox)Forms.Utils.GetControlByName("PCategory", this._form.Controls);
                    //    cbo.SelectedValue = reader.GetInt32(3);
                    //    cbo = (ComboBox)Forms.Utils.GetControlByName("PSite", this._form.Controls);
                    //    cbo.SelectedValue = reader.GetInt32(4);
                    //}
				}
				else
				{
					//TODO - do something here
					sb.Append("Could not retrieve protocol data.");
					sb.Append("\nThe most likely cause is that there is no primary investigator selected.");
					sb.Append("\nEdit the protocol and select a primary investigatory(or admitting MD).");
					MessageBox.Show(this._form, sb.ToString(), "Retrieve Protocol Information Failed", MessageBoxButtons.OK, MessageBoxIcon.Stop);
					return;
				}
				GetPatientActualProjectedPercent(id);
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocol information!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Protocol Information Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetPatientData(int id)
		{
			PatientInfo pi = new PatientInfo();
			string message = "";

			//TODO - have GetPatientInfo throw exception so we don't need message
			pi = CoreLabUtils.GetPatientInfo(id, out message);
			if (pi.ID == -1)
			{
				MessageBox.Show(this._form, message, "Patient Information",
					MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			this._patient.Text = pi.ID.ToString();
			this._mrn.Text = pi.GetMrnOrOtherIdentifier();
			this._patientName.Text = pi.Name;
			if (pi.DateOfBirth == CremaConstants.NullDate)
				this._dob.Text = "";
			else
				this._dob.Text = pi.DateOfBirth.ToShortDateString();

		}

		private void SelectPatient()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Patient"];
			FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);

			fs.ShowDialog(this._form);

			if (fs.DialogResult == DialogResult.OK)
			{
				Console.WriteLine("DialogResult.OK");
				int id = fs.SelectedID;
				Console.WriteLine("Selected ID: " + id.ToString());
				GetPatientData(id);
			}
		}
		#endregion select

		#region search
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;

			ctl.Enabled = false;
			SelectVisitDlg sad = new SelectVisitDlg(this._formInfo.ID);
			sad.Text = this._formInfo.Name + " Search";
			sad.ShowDialog(this._formMain);
			switch (sad.SearchChoice)
			{
				case -1:
					break;
				case 0:
					SelectByStandard();
					break;
				case 1:
					SelectByPatient();
					break;
				case 2:
					SelectByProtocol();
					break;
				case 3:
					SelectByInvestigator();
					break;
			}

			ctl.Enabled = true;
		}

		private void SelectByPatient()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["Patient"];
			_searchType = SearchTypes.Patient;
			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(scr_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				fs.Owner = this._form;
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display patient seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

		}

		private int SelectFromResults(int id, string recordType, string searchBy, string searchResultKey)
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchResultInfo si = (SearchResultInfo)this._formInfo.SearchResultInfo[searchResultKey];
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				//first see if there are any visits for this patient
				string sql = si.SqlCommand + id;

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				if (dt.Rows.Count == 0)
				{
					MessageBox.Show("There are no " + recordType + " for " + searchBy + " id: " + id, "No " + recordType + " Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
					return 0;
				}
				SearchUtils.SetColumnMeta(dt, si);
				FormSearchResultsBase fsr = (FormSearchResultsBase)SearchUtils.GetSearchResultsDialog(si, dt);
				fsr.Text = searchBy + " Search";
				fsr.Controller.BusinessLogic.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(BusinessLogic_ItemSelected);
				fsr.Closing += new CancelEventHandler(fsr_Closing);
				fsr.Owner = this._form;
				fsr.Show();
				return 1;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not retrieve select results.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Select Results Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return 0;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void SelectByStandard()
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this._formInfo.SearchFormInfo["ProtocolVisitAdmission"];

			try
			{
				FormSearchBase fs = (FormSearchBase)SearchUtils.GetSearchDialog(si);
				fs.Owner = this._form;
				fs.Controller.ItemSelected += new ctsu.BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
				fs.Closing += new CancelEventHandler(fs_Closing);
				IsSearchVisible = true;
				fs.Show();
			}
			catch (Exception ex)
			{
				sb.Append("Could not display admission visit seach dialog!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Display Search Dialog Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void scr_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			string recordType = "";
			string searchBy = "";
			string searchResultsKey = "";

			switch (this._searchType)
			{
				case SearchTypes.Investigator:
					recordType = "Admissions";
					searchBy = "Protocol";
					searchResultsKey = "ProtocolAdmissionVisit";
					break;
				case SearchTypes.Patient:
					recordType = "Admissions";
					searchBy = "Patient";
					searchResultsKey = "PatientAdmissionVisit";
					break;
				case SearchTypes.Protocol:
					recordType = "Admissions";
					searchBy = "Protocol";
					searchResultsKey = "ProtocolAdmissionVisit";
					break;
			}
			if (e.ID > 0)
				SelectFromResults(e.ID, recordType, searchBy, searchResultsKey);
		}

		private void BusinessLogic_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				if (this.GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fsr_Closing(object sender, CancelEventArgs e)
		{

		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
			else
				Console.WriteLine("ID: " + e.ID);
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}
		#endregion search

	}
}
